package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.lawyer.config.BaseConfigUrlBean;
import com.lawyer.entity.User;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.model.TokenInfo;
import com.lawyer.model.WxLoginModel;
import com.lawyer.model.WxUserInfo;
import com.lawyer.model.wx.WxPhone;
import com.lawyer.repository.UserRepository;
import com.lawyer.uitls.WXUtils;

@RestController
@Api(tags = "用户端登陆注册")
@RequestMapping(value = "/userFactory")
public class UserLoginController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BaseConfigUrlBean baseConfigUrlBean;

	@Autowired
	private UserRepository userRepository;

	protected final String SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=wx2de5288e1d9810c3&secret=a754c540848973bf56980595e004442c&grant_type=authorization_code&js_code=";

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "用户端授权登陆登陆", notes = "用户端授权登陆登陆")
	public HttpEntity<?> login(@RequestBody WxLoginModel model) {
		Message msg = new Message();
		Map<String, Object> map = new HashMap<String, Object>();

		RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.put("Content-Type", Lists.newArrayList(MediaType.APPLICATION_JSON_VALUE));
		String url = SESSION_URL + model.getCode();
		ResponseEntity<String> wxEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
		System.out.println("userinfo==============" + wxEntity.getBody());
		ReadContext ctx = JsonPath.parse(wxEntity.getBody());
		try {
			String sessionKey = ctx.read("$.session_key");
			String openid = ctx.read("$.openid");

			WxUserInfo userInfo = WXUtils.getUserInfo(model.getEncryptedData(), sessionKey, model.getIv());
			User user = userRepository.findOne(openid);
			if (user == null) {
				User saveUser = new User();
				saveUser.setHeaderIco(userInfo.getAvatarUrl());
				saveUser.setId(openid);
				saveUser.setNickName(userInfo.getNickName());
				saveUser.setEnabled(true);
				saveUser.setUsername(openid);
				saveUser.setShareCount(0);
				saveUser.setBalance(0D);
				saveUser.setUsableTime(0L);
				saveUser.setIsCallPay(false);
				saveUser.setSessionKey(sessionKey);
				saveUser.setPassword("WYAyPRZAKOqJnYnD0A9vC6hMs2yArey0zu2X+65C9Y7QfoWURZh7F1k==");
				userRepository.save(saveUser);
				saveUser.setId(null);
				// 保存到oatuh2
				new RestTemplate().exchange(baseConfigUrlBean.getRegister(), HttpMethod.POST, new HttpEntity<>(saveUser,headers), Message.class);
			}

			// 获取token

			User findUser = userRepository.findOne(openid);
			findUser.setSessionKey(sessionKey);
			findUser.setPassword("WYAyPRZAKOqJnYnD0A9vC6hMs2yArey0zu2X+65C9Y7QfoWURZh7F1k==");
			ResponseEntity<TokenInfo> entity = restTemplate.exchange(baseConfigUrlBean.getLogin(), HttpMethod.POST, new HttpEntity<>(findUser,headers), TokenInfo.class);
			TokenInfo info = entity.getBody();
			findUser.setPassword(null);
			map.put("tokenInfo", info);
			map.put("userInfo", findUser);
			msg.setData(map);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);

		}
		return new ResponseEntity<>(msg, HttpStatus.OK);

	}

	@RequestMapping(value = "/authorized", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "授权手机", notes = "授权手机")
	public HttpEntity<?> authorized(String encryptedData, String iv, String openid) {
		Message msg = new Message();
		User user = userRepository.findOne(openid);

		if (user != null && StringUtils.isNotEmpty(user.getSessionKey())) {

			WxPhone wxPhone = WXUtils.unEncryptedData(encryptedData, user.getSessionKey(), iv);
			user.setPhone(wxPhone.getPhoneNumber());
			userRepository.save(user);
		} else {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("账号已存在");
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);

	}


	@RequestMapping(value = "/check", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "判断用户账号是否已注册", notes = "输入13位手机号码")
	public HttpEntity<?> check(String phone) {
		Message msg = new Message();
		User findUser = userRepository.findByUsername(phone);
		if (findUser == null) {
			msg.setCode(MessageConstant.SUCCESS_CODE);
			msg.setMessage("账号不存在");
		} else {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("账号已存在");
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);

	}

}
